package com.heimali.happyreader.wraper;

import java.net.URI;
import java.util.HashMap;

import org.apache.http.client.utils.URIUtils;

import com.heimali.happyreader.config.Constants;
import com.heimali.happyreader.http.JsonParser;
import com.heimali.happyreader.model.LoginUserInfo;
import com.heimali.happyreader.utils.HttpUtils;
import com.heimali.happyreader.utils.SystemUtils;
import com.heimali.happyreader.utils.UserUtils;

public class UserCenterWraper extends BaseWraper {
	private static final String TAG = "LoginWraper";
	public static enum TYPE {LOGIN, REGISTER} ;
	
	public UserCenterWraper(URI uri, Callback callback) {
		super(uri, callback);
	}

	public UserCenterWraper(String username, String password, TYPE type, Callback callback) {
		super();
		try {
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("type", getType(type));
			params.put("username", UserUtils.getUserName(username, password));
			params.put("password", UserUtils.getPassword(password, username));

			this.uri = URIUtils.createURI(Constants.PROTOCOL, Constants.HOST, Constants.PORT, Constants.LoginIntfPath,
					HttpUtils.buildQuery(params), null);
			this.callback = callback;
		} catch (Exception e) {
			e.printStackTrace();
			SystemUtils.Log(TAG, e.getMessage());
		}
	}

	@Override
	protected void onExecute(String result) {
		try {
			LoginUserInfo userInfo = JsonParser.loginInfoParser(result);

			if (userInfo == null) {
				callback.onFail(Constants.E_SERVER_BUSY, null);
				return;
			}

			if (userInfo.suc == 1) {
				callback.onSuccess(userInfo);
			} else {
				callback.onFail(UserUtils.USERNAME_OR_PASSWORD_ERROR, null);
			}

		} catch (Exception e) {
			e.printStackTrace();
			SystemUtils.Log("Exception", e.getMessage());
			callback.onFail(Constants.E_UNKNOWN_ERROR, e.getMessage());
		}
	}
	
	private String getType(TYPE type) {
		return (type == TYPE.REGISTER) ? "adduser" : "checkuser";
	}

}
